# -*- coding: utf-8 -*-
# @Author: Zach-Pineappleman
# @E-mail: 354399824@qq.com
# @Date:   2025-03-13 21:22:51
# @File_name:voice_detector.py
# @Last Modified by:   Zach-Pineappleman
# @Last Modified time: 2025-03-13 21:25:50

# voice_detector.py
# 语音识别

import threading
import pyaudio
import wave
import numpy as np
from config import *

class VoiceDetector:
    def __init__(self, app):
        self.app = app
        self.running = False
        self.audio = pyaudio.PyAudio()
        self.stream = None
        self.energy_threshold = 300

    def start(self):
        self.running = True
        self.stream = self.audio.open(format=FORMAT,
                                      channels=CHANNELS,
                                      rate=RATE,
                                      input=True,
                                      frames_per_buffer=CHUNK)
        threading.Thread(target=self.listen).start()

    def listen(self):
        while self.running:
            data = self.stream.read(CHUNK)
            energy = np.mean(np.abs(np.frombuffer(data, dtype=np.int16)))
            if energy > self.energy_threshold:
                print("检测到语音")
                self.app.handle_voice_input(data)

    def stop(self):
        self.running = False
        self.stream.stop_stream()
        self.stream.close()
        self.audio.terminate()